package com.example.demo.example.map;

import com.example.demo.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@NotThreadSafe
public class CurrentHashMapExample {

    //线程数
    public static int clientTotal = 5000;

    //并发线程数
    private static int threadTotal = 200;

    Map map = new ConcurrentHashMap();

    //计数方法
    private void add(int index){

        map.put("刘"+index,1);

    }


    public static void main(String[] args) throws Exception{
        CurrentHashMapExample hme = new CurrentHashMapExample();
        //模拟并发执行

        //1.定义一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //2.定义信号量(定义出并发的数)
        final Semaphore semaphore = new Semaphore(threadTotal);
        //3.定义计数器闭锁
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        //4.将请求放到线程池中,应用lambda
        for (int i = 0; i < clientTotal; i++) {
            //引入信号量
            final int index = i;
            executorService.execute(() ->{
                try {

                    semaphore.acquire();
                    hme.add(index);
                    semaphore.release();
                }catch (Exception e){
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("size:{}", hme.map.size());
    }
}
